package org.rc.server;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.rc.cache.AudioTextClientCache;
import org.rc.cache.FrontTextSessionCache;
import org.rc.cache.PersonnelNameCache;
import org.rc.cache.SlpTextSessionCache;
import org.rc.client.AudioTextClient;
import org.rc.component.DtComponent;
import org.rc.config.WsSessionConfig;
import org.rc.dto.FrontCommandDto;
import org.rc.dto.KeyWordGroup;
import org.rc.entity.Mic;
import org.rc.entity.RoomDev;
import org.rc.enums.DevType;
import org.rc.service.MicService;
import org.rc.service.RoomDevService;
import org.rc.util.RequestParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Map;


/**
 * web端和服务的的ws连接
 */
@Slf4j
@ServerEndpoint(value = "/front-text",configurator = WsSessionConfig.class)
@Component
@Scope("prototype")
public class RemoteCommandTextEndpoint {

    @Value("${audio.text.endpoint}")
    private String textEndpoint;

    @Autowired
    private DtComponent dtComponent;

    @Autowired
    private RoomDevService roomDevService;

    @Autowired
    private MicService micService;

    @Autowired
    private PersonnelNameCache personnelNameCache;

    @OnOpen
    public void onOpen(Session session, EndpointConfig config) throws IOException {
        String param = session.getQueryString();
        Map<String,String> paramsMap = RequestParamUtil.regularParam2Map(param);
        String roomId = paramsMap.get("roomId");
        log.info("接收到远程指挥连接，roomId --->{}",roomId);
        List<RoomDev> roomDev = roomDevService.getRoomDevByRoomIdAndDevId(DevType.MIC.getType(),Long.parseLong(roomId));
        if(CollectionUtils.isEmpty(roomDev)){
            log.warn("当前房间尚未绑定麦克风，断开连接");
            session.getBasicRemote().sendText("当前房间尚未绑定麦克风，断开连接");
            session.close();
            return;
        }
        Mic mic = micService.getByMicId(roomDev.get(0).getDevId());
        String mac = mic.getMac();
        session.getUserProperties().put("mac",mac);
        FrontTextSessionCache.add(mac,session);
        AudioTextClient client = AudioTextClientCache.getClient(mac);
        if(null == client || client.getConnection() ==null || !client.getConnection().isOpen()){
            List<KeyWordGroup> keyWordDic = dtComponent.getKeyWordDic();
            log.debug("获取到关键词预警配置--->{}",JSONObject.toJSONString(keyWordDic));
            try{
                URI uri = new URI(textEndpoint);
                client = new AudioTextClient(uri,mac,keyWordDic,personnelNameCache.getNames());
                AudioTextClientCache.saveClient(mac,client);
            }catch (Exception e){
                log.error("和麦克风转写结果服务建立连接出现异常，e--->",e);
                AudioTextClientCache.delClient(mac);
            }
        }else{
            log.info("当前麦克风转写请求连接已经建立");
        }
    }

    @OnMessage
    public void onMessage(String text, Session session) throws IOException {
        String mac = session.getUserProperties().get("mac").toString();
        if(StringUtils.isNotEmpty(text) && !"heartBeat".equals(text)){
            log.info("接收到远程指挥的指令--->{}",text);
            FrontCommandDto frontCommandDto = new FrontCommandDto("command",text);
            SlpTextSessionCache.sendText(mac,JSONObject.toJSONString(frontCommandDto));
        }
    }

    @OnClose
    public void onClose(Session session){
        String mac = session.getUserProperties().get("mac").toString();
        FrontTextSessionCache.removeSession(mac,session);
        List<Session> sessions =  FrontTextSessionCache.getSessions(mac);
        if(CollectionUtils.isEmpty(sessions)){
            log.info("当前无任何请求转写文本客户端连接，关闭拉取文本连接");
            AudioTextClientCache.delClient(mac);
        }
    }

    @OnError
    public void onError(Session session, Throwable th){
        log.error("连接发生异常，e--->",th);
        String mac = session.getUserProperties().get("mac").toString();
        FrontTextSessionCache.removeSession(mac,session);
        List<Session> sessions =  FrontTextSessionCache.getSessions(mac);
        if(CollectionUtils.isEmpty(sessions)){
            log.info("当前无任何请求转写文本客户端连接，关闭拉取文本连接");
            AudioTextClientCache.delClient(mac);
        }
    }

}
